use egui::{pos2, Color32, Pos2, Rect, TextureOptions, Vec2};
use egui_fak_nodes::{graph::{Graph, GraphViewer}, node::NodeViewer, ui::FakViewer};

struct App {
    viewer:FakViewer<BPNode>
}

impl App {
    pub fn new(cx:&egui::Context)->Self{
        let graph_viewer = Box::new(BPGraphViewer{});
        let image = image::ImageReader::open("res/BlueprintBackground.png").unwrap().decode().unwrap().to_rgba8();
        let (width, height) = image.dimensions();

        let node_viewer = Box::new(BPNodeViewer{
            texture:cx.load_texture("bp_head_bg", egui::ColorImage::from_rgba_unmultiplied([width as usize, height as usize], &image), TextureOptions::NEAREST_REPEAT)
        });
        let mut graph_data = Graph::new();
        let mut node = egui_fak_nodes::node::Node::new(BPNode{});
        node.set_position(Pos2::new(500., 100.));
        graph_data.add_node(node);

        let mut node = egui_fak_nodes::node::Node::new(BPNode{});
        node.set_position(Pos2::new(100., 100.));
        graph_data.add_node(node);
        let viewer = FakViewer::new(graph_viewer, node_viewer).with(graph_data);
        App {
            viewer
        }
    }
}

struct BPNode {}

struct BPNodeViewer {
    texture:egui::TextureHandle,
}

impl NodeViewer<BPNode> for BPNodeViewer {
    fn draw_header(&mut self, node:&mut egui_fak_nodes::prelude::Node<BPNode>, ui:&mut egui::Ui) {
        let rect = ui.available_rect_before_wrap();
        ui.painter().image(self.texture.id(), rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::RED);
        // let resp = ui.label("BPNodeLong Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long ")
        let label = egui::Label::new("BPNodeLong Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long ").wrap_mode(egui::TextWrapMode::Extend);
        //适应文字大小，要单行显示
        ui.add(label); 
    }
}

struct BPGraphViewer {}

impl GraphViewer<BPNode> for BPGraphViewer {}


impl eframe::App for App {
    fn update(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
        egui::CentralPanel::default().show(ctx, |ui| {
            self.viewer.show(ui);
        });
    }
}
fn main() -> eframe::Result<()> {
    let native_options = eframe::NativeOptions {
        viewport: egui::ViewportBuilder::default()
            .with_inner_size([400.0, 300.0])
            .with_min_inner_size([300.0, 220.0]),
        ..Default::default()
    };

    eframe::run_native(
        "egui-snarl demo",
        native_options,
        Box::new(|cx| Ok(Box::new(App::new(&cx.egui_ctx)))),
    )
}